<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天机器人 | 前端实现</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        
        header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 1rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            z-index: 2;
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .logo-icon {
            font-size: 2rem;
            background: rgba(255, 255, 255, 0.15);
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .connection-status {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 15px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .connected .status-indicator {
            background-color: #4caf50;
            box-shadow: 0 0 8px #4caf50;
        }
        
        .disconnected .status-indicator {
            background-color: #f44336;
        }
        
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .chat-container {
            flex: 1;
            min-width: 300px;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        .chat-header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            font-size: 1.1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .chat-box {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            max-height: 60vh;
            min-height: 300px;
            background-color: #f9f9f9;
            position: relative;
            scroll-behavior: smooth;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 12px 16px;
            border-radius: 18px;
            max-width: 85%;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease;
            clear: both;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .user-message {
            background-color: #0084ff;
            color: white;
            float: right;
            border-bottom-right-radius: 4px;
        }
        
        .ai-message {
            background-color: #f0f0f0;
            float: left;
            border-bottom-left-radius: 4px;
            color: #333;
        }
        
        .input-area {
            padding: 15px;
            background-color: #fff;
            border-top: 1px solid #eee;
            display: flex;
            gap: 10px;
        }
        
        #user-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 24px;
            outline: none;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        #user-input:focus {
            border-color: #0084ff;
            box-shadow: 0 0 0 2px rgba(0, 132, 255, 0.2);
        }
        
        #send-button {
            background-color: #0084ff;
            color: white;
            border: none;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            font-size: 1.1rem;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        #send-button:hover {
            background-color: #0073e6;
        }
        
        .typing-indicator {
            display: none;
            padding: 12px 16px;
            background-color: #f0f0f0;
            border-radius: 18px;
            max-width: 120px;
            margin-bottom: 15px;
            float: left;
            animation: fadeIn 0.3s ease;
        }
        
        .typing-indicator span {
            height: 8px;
            width: 8px;
            background-color: #aaa;
            border-radius: 50%;
            display: inline-block;
            margin-right: 4px;
            animation: bounce 1.5s infinite;
        }
        
        .typing-indicator span:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-indicator span:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }
        
        .error-message {
            display: none;
            background-color: #ffebee;
            color: #c62828;
            padding: 12px 16px;
            border-radius: 8px;
            margin: 10px 0;
            text-align: center;
            animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
        }
        
        @keyframes shake {
            10%, 90% { transform: translateX(-1px); }
            20%, 80% { transform: translateX(2px); }
            30%, 50%, 70% { transform: translateX(-4px); }
            40%, 60% { transform: translateX(4px); }
        }
        
        .placeholder {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #aaa;
            font-size: 1.1rem;
            text-align: center;
            width: 100%;
            padding: 0 20px;
        }
        
        .features {
            flex: 1;
            min-width: 280px;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            padding: 25px;
            height: fit-content;
        }
        
        .features h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .features ul {
            list-style: none;
        }
        
        .features li {
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .features li::before {
            content: "✓";
            color: #0084ff;
            font-weight: bold;
            font-size: 1.3rem;
        }
        
        .footer {
            margin-top: auto;
            background-color: #2c3e50;
            color: rgba(255, 255, 255, 0.7);
            padding: 20px;
            text-align: center;
            font-size: 0.9rem;
        }
        
        .code-header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            border-radius: 12px 12px 0 0;
            margin: 40px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .code-block {
            background-color: #1e1e1e;
            color: #d4d4d4;
            border-radius: 0 0 12px 12px;
            padding: 20px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            line-height: 1.5;
            font-size: 0.95rem;
        }
        
        .code-tag {
            color: #9cdcfe;
        }
        
        .code-keyword {
            color: #c586c0;
        }
        
        .code-function {
            color: #dcdcaa;
        }
        
        .code-comment {
            color: #6a9955;
        }
        
        .code-string {
            color: #ce9178;
        }
        
        .code-constant {
            color: #569cd6;
        }
        
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .chat-box {
                max-height: 50vh;
            }
        }
    </style>
</head>
<body>
    <header>
        <div class="header-content">
            <div class="logo">
                <div class="logo-icon">🤖</div>
                <h1>AI聊天机器人</h1>
            </div>
            <div class="connection-status" id="status-indicator">
                <div class="status-indicator"></div>
                <span>正在连接...</span>
            </div>
        </div>
    </header>
    
    <div class="container">
        <div class="chat-container">
            <div class="chat-header">
                <span>对话面板</span>
                <div id="server-status">正在检测服务状态...</div>
            </div>
            
            <div class="chat-box" id="chat-box">
                <div id="error-message" class="error-message"></div>
                <div id="typing-indicator" class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
                <div id="placeholder" class="placeholder">
                    <p>发送消息开始与AI对话</p>
                </div>
                
                <!-- 示例消息 -->
                <div class="message ai-message">
                    您好！我是一个人工智能助手。有什么问题我可以帮助您解答吗？
                </div>
                <div class="message user-message">
                    你好，请介绍一下你自己吧！
                </div>
                <div class="message ai-message">
                    我是基于先进AI模型的智能助手，能够理解和生成自然语言文本。我可以回答各种问题、提供建议、解释概念、协助完成任务等。只要告诉我您需要什么帮助就好！
                </div>
            </div>
            
            <div class="input-area">
                <input type="text" id="user-input" placeholder="输入您的问题...">
                <button id="send-button">➤</button>
            </div>
        </div>
        
        <div class="features">
            <h2>功能特性</h2>
            <ul>
                <li>动态适应不同环境（开发/生产）</li>
                <li>智能错误处理与友好提示</li>
                <li>实时连接状态监测</li>
                <li>自动滚动与消息动画</li>
                <li>支持本地和远程API端点</li>
                <li>响应超时处理机制</li>
                <li>移动设备友好设计</li>
                <li>持续自动检测后端状态</li>
            </ul>
        </div>
    </div>
    
    <div class="container">
        <div class="code-header">
            <h3>聊天机器人前端脚本源码</h3>
            <div>自动适应环境 · 增强错误处理 · 连接状态检测</div>
        </div>
        <div class="code-block">
            <pre><code><span class="code-tag">&lt;script&gt;</span>
<span class="code-comment">    // 使用动态API基础路径，自动适应开发和生产环境</span>
    <span class="code-keyword">const</span> <span class="code-constant">API_BASE_URL</span> = window.location.origin + <span class="code-string">'/api'</span>;
    <span class="code-keyword">const</span> <span class="code-constant">IS_LOCAL</span> = window.location.hostname === <span class="code-string">'localhost'</span> || 
                     window.location.hostname === <span class="code-string">'127.0.0.1'</span>;

    <span class="code-comment">// DOM元素引用</span>
    <span class="code-keyword">const</span> <span class="code-constant">chatBox</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'chat-box'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">userInput</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'user-input'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">sendButton</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'send-button'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">typingIndicator</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'typing-indicator'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">errorMessage</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'error-message'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">placeholder</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'placeholder'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">statusIndicator</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'status-indicator'</span>);
    <span class="code-keyword">const</span> <span class="code-constant">serverStatus</span> = document.<span class="code-function">getElementById</span>(<span class="code-string">'server-status'</span>);
    
    <span class="code-comment">// 显示/隐藏占位符</span>
    <span class="code-keyword">function</span> <span class="code-function">updatePlaceholder</span>() {
        placeholder.style.display = chatBox.children.length <= 2 ? <span class="code-string">'block'</span> : <span class="code-string">'none'</span>;
    }
    
    <span class="code-comment">// 添加消息到聊天框</span>
    <span class="code-keyword">function</span> <span class="code-function">addMessage</span>(content, isUser = <span class="code-keyword">false</span>, isError = <span class="code-keyword">false</span>) {
        <span class="code-keyword">if</span> (isError) {
            <span class="code-comment">// 显示错误消息</span>
            errorMessage.innerHTML = content;
            errorMessage.style.display = <span class="code-string">'block'</span>;
            
            <span class="code-comment">// 10秒后自动隐藏错误</span>
            setTimeout(() => {
                errorMessage.style.display = <span class="code-string">'none'</span>;
            }, 10000);
        } <span class="code-keyword">else</span> {
            <span class="code-keyword">const</span> <span class="code-constant">messageDiv</span> = document.<span class="code-function">createElement</span>(<span class="code-string">'div'</span>);
            messageDiv.classList.<span class="code-function">add</span>(<span class="code-string">'message'</span>);
            messageDiv.classList.<span class="code-function">add</span>(isUser ? <span class="code-string">'user-message'</span> : <span class="code-string">'ai-message'</span>);
            messageDiv.textContent = (isUser ? <span class="code-string">'您: '</span> : <span class="code-string">'AI: '</span>) + content;
            chatBox.<span class="code-function">appendChild</span>(messageDiv);
            
            <span class="code-comment">// 移除占位符并滚动到底部</span>
            <span class="code-function">updatePlaceholder</span>();
            chatBox.scrollTop = chatBox.scrollHeight;
        }
    }
    
    <span class="code-comment">// 显示更友好的错误提示</span>
    <span class="code-keyword">function</span> <span class="code-function">showFriendlyError</span>(message) {
        <span class="code-comment">// 更新状态指示器</span>
        statusIndicator.textContent = <span class="code-string">`⚠️ ${message}`</span>;
        statusIndicator.classList.<span class="code-function">add</span>(<span class="code-string">'disconnected'</span>);
        serverStatus.textContent = <span class="code-string">"服务连接失败"</span>;
        serverStatus.style.color = <span class="code-string">"#f44336"</span>;
        
        <span class="code-comment">// 在聊天框中添加指导性消息</span>
        <span class="code-keyword">if</span> (chatBox.querySelectorAll(<span class="code-string">'.message'</span>).length <= 2) {
            <span class="code-function">addMessage</span>(<span class="code-string">'连接问题：请尝试以下操作：'</span>, <span class="code-keyword">false</span>, <span class="code-keyword">false</span>);
            <span class="code-function">addMessage</span>(<span class="code-string">'1. 检查网络连接'</span>, <span class="code-keyword">false</span>, <span class="code-keyword">false</span>);
            <span class="code-function">addMessage</span>(<span class="code-string">'2. 刷新页面重试'</span>, <span class="code-keyword">false</span>, <span class="code-keyword">false</span>);
            
            <span class="code-keyword">if</span> (<span class="code-constant">IS_LOCAL</span>) {
                <span class="code-function">addMessage</span>(<span class="code-string">'3. 确保后端服务已启动'</span>, <span class="code-keyword">false</span>, <span class="code-keyword">false</span>);
            }
        }
    }
    
    <span class="code-comment">// 检查与后端的连接</span>
    <span class="code-keyword">async</span> <span class="code-keyword">function</span> <span class="code-function">checkConnection</span>() {
        <span class="code-keyword">try</span> {
            <span class="code-keyword">const</span> <span class="code-constant">response</span> = <span class="code-keyword">await</span> fetch(`${<span class="code-constant">API_BASE_URL</span>}/health`, {
                method: <span class="code-string">'GET'</span>,
                headers: { <span class="code-string">'Content-Type'</span>: <span class="code-string">'application/json'</span> }
            });
            
            <span class="code-keyword">if</span> (response.ok) {
                <span class="code-keyword">const</span> <span class="code-constant">data</span> = <span class="code-keyword">await</span> response.<span class="code-function">json</span>();
                statusIndicator.innerHTML = `✅ 已连接 | 状态: ${data.status || <span class="code-string">'正常'</span>}`;
                statusIndicator.classList.<span class="code-function">add</span>(<span class="code-string">'connected'</span>);
                statusIndicator.classList.<span class="code-function">remove</span>(<span class="code-string">'disconnected'</span>);
                serverStatus.textContent = <span class="code-string">"服务运行正常"</span>;
                serverStatus.style.color = <span class="code-string">"#4caf50"</span>;
            } <span class="code-keyword">else</span> {
                <span class="code-keyword">throw</span> <span class="code-keyword">new</span> <span class="code-function">Error</span>(`服务响应异常: HTTP ${response.status}`);
            }
        } <span class="code-keyword">catch</span> (error) {
            <span class="code-comment">// 分类处理不同类型的错误</span>
            <span class="code-keyword">let</span> <span class="code-constant">errorMsg</span> = `无法连接到AI服务`;
            
            <span class="code-keyword">if</span> (error.name === <span class="code-string">'TypeError'</span> &amp;&amp; error.message === <span class="code-string">'Failed to fetch'</span>) {
                errorMsg += <span class="code-string">" (网络错误)"</span>;
            } <span class="code-keyword">else</span> {
                errorMsg += `: ${error.message}`;
            }
            
            <span class="code-function">showFriendlyError</span>(errorMsg);
            
            <span class="code-comment">// 本地开发时提示更具体</span>
            <span class="code-keyword">if</span> (<span class="code-constant">IS_LOCAL</span>) {
                <span class="code-function">addMessage</span>(`本地开发提示：确保后端在端口 8000 上运行`, <span class="code-keyword">false</span>, <span class="code-keyword">true</span>);
            }
        }
    }
    
    <span class="code-comment">// 发送消息到后端</span>
    <span class="code-keyword">async</span> <span class="code-keyword">function</span> <span class="code-function">sendMessage</span>() {
        <span class="code-keyword">const</span> <span class="code-constant">message</span> = userInput.value.trim();
        <span class="code-keyword">if</span> (!message) <span class="code-keyword">return</span>;
        
        <span class="code-comment">// 添加用户消息到聊天界面</span>
        <span class="code-function">addMessage</span>(message, <span class="code-keyword">true</span>);
        userInput.value = <span class="code-string">''</span>;
        userInput.<span class="code-function">focus</span>();
        
        <span class="code-comment">// 显示AI正在输入的状态</span>
        typingIndicator.style.display = <span class="code-string">'flex'</span>;
        chatBox.scrollTop = chatBox.scrollHeight;
        
        <span class="code-comment">// 创建AbortController用于超时处理</span>
        <span class="code-keyword">const</span> <span class="code-constant">controller</span> = <span class="code-keyword">new</span> <span class="code-function">AbortController</span>();
        <span class="code-keyword">const</span> <span class="code-constant">timeoutId</span> = <span class="code-function">setTimeout</span>(() => controller.<span class="code-function">abort</span>(), 15000);
        
        <span class="code-keyword">try</span> {
            <span class="code-comment">// 向后端发送请求（使用统一的基础路径）</span>
            <span class="code-keyword">const</span> <span class="code-constant">response</span> = <span class="code-keyword">await</span> fetch(`${<span class="code-constant">API_BASE_URL</span>}/chat`, {
                method: <span class="code-string">'POST'</span>,
                headers: { <span class="code-string">'Content-Type'</span>: <span class="code-string">'application/json'</span> },
                body: JSON.<span class="code-function">stringify</span>({ user_input: message }),
                signal: controller.signal
            });
            
            <span class="code-keyword">if</span> (!response.ok) {
                <span class="code-keyword">const</span> <span class="code-constant">errorDetail</span> = <span class="code-keyword">await</span> response.<span class="code-function">json</span>().<span class="code-function">catch</span>(() => <span class="code-keyword">null</span>);
                <span class="code-keyword">throw</span> <span class="code-keyword">new</span> <span class="code-function">Error</span>(errorDetail?.detail || `请求失败: HTTP ${response.status}`);
            }
            
            <span class="code-keyword">const</span> <span class="code-constant">data</span> = <span class="code-keyword">await</span> response.<span class="code-function">json</span>();
            
            <span class="code-keyword">if</span> (data.status === <span class="code-string">'success'</span>) {
                <span class="code-function">addMessage</span>(data.response, <span class="code-keyword">false</span>);
            } <span class="code-keyword">else</span> {
                <span class="code-keyword">throw</span> <span class="code-keyword">new</span> <span class="code-function">Error</span>(data.detail || <span class="code-string">'后端服务处理失败'</span>);
            }
        } <span class="code-keyword">catch</span> (error) {
            <span class="code-comment">// 分类处理错误类型</span>
            <span class="code-keyword">let</span> <span class="code-constant">errorMsg</span> = <span class="code-string">'网络请求失败'</span>;
            
            <span class="code-keyword">if</span> (error.name === <span class="code-string">'AbortError'</span>) {
                errorMsg = <span class="code-string">'响应超时，请稍后重试'</span>;
            } <span class="code-keyword">else</span> <span class="code-keyword">if</span> (error.message.<span class="code-function">includes</span>(<span class="code-string">'Failed to fetch'</span>)) {
                errorMsg = <span class="code-string">'无法连接到服务器，请检查网络连接'</span>;
            } <span class="code-keyword">else</span> {
                errorMsg = `请求错误: ${error.message}`;
            }
            
            <span class="code-comment">// 显示错误提示</span>
            <span class="code-function">addMessage</span>(errorMsg, <span class="code-keyword">false</span>, <span class="code-keyword">true</span>);
        } <span class="code-keyword">finally</span> {
            <span class="code-comment">// 隐藏"正在输入"状态</span>
            typingIndicator.style.display = <span class="code-string">'none'</span>;
            <span class="code-function">clearTimeout</span>(timeoutId);
            <span class="code-function">updatePlaceholder</span>();
        }
    }
    
    <span class="code-comment">// 事件监听器</span>
    sendButton.<span class="code-function">addEventListener</span>(<span class="code-string">'click'</span>, sendMessage);
    
    userInput.<span class="code-function">addEventListener</span>(<span class="code-string">'keypress'</span>, (e) => {
        <span class="code-keyword">if</span> (e.key === <span class="code-string">'Enter'</span>) <span class="code-function">sendMessage</span>();
    });
    
    <span class="code-comment">// 处理页面可见性变化</span>
    document.<span class="code-function">addEventListener</span>(<span class="code-string">'visibilitychange'</span>, () => {
        <span class="code-keyword">if</span> (document.visibilityState === <span class="code-string">'visible'</span>) {
            <span class="code-function">checkConnection</span>();
        }
    });
    
    <span class="code-comment">// 初始化</span>
    <span class="code-function">checkConnection</span>();
    <span class="code-function">updatePlaceholder</span>();
    userInput.<span class="code-function">focus</span>();
    
    <span class="code-comment">// 定时检查状态（每30秒）</span>
    <span class="code-function">setInterval</span>(checkConnection, 30000);
<span class="code-tag">&lt;/script&gt;</span></code></pre>
        </div>
    </div>
    
    <footer class="footer">
        <p>AI聊天机器人前端实现 &copy; 2025 | 自适应环境 | 增强错误处理 | 实时连接检测</p>
    </footer>
        <script>
    // 使用动态API基础路径，自动适应开发和生产环境
// 使用动态API基础路径，自动适应开发和生产环境
        const IS_FILE_PROTOCOL = window.location.protocol === 'file:';
        const API_BASE_URL = IS_FILE_PROTOCOL ? 
            'http://localhost:8000/api' : // 默认本地开发地址
            window.location.origin + '/api';
        
        const IS_LOCAL = window.location.hostname === 'localhost' || 
                         window.location.hostname === '127.0.0.1' ||
                         IS_FILE_PROTOCOL;

        // DOM元素引用
        const chatBox = document.getElementById('chat-box');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const typingIndicator = document.getElementById('typing-indicator');
        const errorMessage = document.getElementById('error-message');
        const placeholder = document.getElementById('placeholder');
        const statusIndicator = document.getElementById('status-indicator');
        const serverStatus = document.getElementById('server-status');
        
        // 显示/隐藏占位符
        function updatePlaceholder() {
            placeholder.style.display = chatBox.children.length <= 2 ? 'block' : 'none';
        }
        
        // 添加消息到聊天框
        function addMessage(content, isUser = false, isError = false) {
            if (isError) {
                // 显示错误消息
                errorMessage.innerHTML = content;
                errorMessage.style.display = 'block';
                
                // 10秒后自动隐藏错误
                setTimeout(() => {
                    errorMessage.style.display = 'none';
                }, 10000);
            } else {
                const messageDiv = document.createElement('div');
                messageDiv.classList.add('message');
                messageDiv.classList.add(isUser ? 'user-message' : 'ai-message');
                messageDiv.textContent = (isUser ? '您: ' : 'AI: ') + content;
                chatBox.appendChild(messageDiv);
                
                // 移除占位符并滚动到底部
                updatePlaceholder();
                chatBox.scrollTop = chatBox.scrollHeight;
            }
        }
        
        // 更新连接状态
        function updateConnectionStatus(text, color) {
            statusIndicator.textContent = text;
            statusIndicator.style.backgroundColor = color;
            statusIndicator.classList.toggle('connected', color === '#4caf50');
        }
        
        // 检查与后端的连接
        async function checkConnection() {
            // 如果是file协议，显示特殊提示
            if (IS_FILE_PROTOCOL) {
                serverStatus.textContent = "File协议模式 - 需要本地后端";
                serverStatus.style.color = "#ff9800";
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/health`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    updateConnectionStatus(`✅ 已连接 | 状态: ${data.status || '正常'}`, '#4caf50');
                    serverStatus.textContent = "服务运行正常";
                    serverStatus.style.color = "#4caf50";
                    
                    if (IS_FILE_PROTOCOL) {
                        serverStatus.textContent += " (File协议)";
                    }
                } else {
                    throw new Error(`服务响应异常: HTTP ${response.status}`);
                }
            } catch (error) {
                // 分类处理不同类型的错误
                let errorMsg = `无法连接到AI服务`;
                
                if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
                    errorMsg += " (网络错误)";
                } else {
                    errorMsg += `: ${error.message}`;
                }
                
                // 特殊处理file协议错误
                if (IS_FILE_PROTOCOL) {
                    errorMsg += "<br>注意：您正在使用file://协议访问，需要启动本地后端服务";
                }
                
                updateConnectionStatus(`⚠️ ${errorMsg}`, '#f44336');
                serverStatus.textContent = "服务连接失败";
                serverStatus.style.color = "#f44336";
                
                // 本地开发时提示更具体
                if (IS_LOCAL) {
                    addMessage(`本地开发提示：确保后端在端口 8000 上运行`, false, true);
                }
            }
        }
        
        // 发送消息到后端
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;
            
            // 添加用户消息到聊天界面
            addMessage(message, true);
            userInput.value = '';
            userInput.focus();
            
            // 显示AI正在输入的状态
            typingIndicator.style.display = 'flex';
            chatBox.scrollTop = chatBox.scrollHeight;
            
            try {
                // 向后端发送请求（使用统一的基础路径）
                const response = await fetch(`${API_BASE_URL}/chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ user_input: message })
                });
                
                if (!response.ok) {
                    const errorDetail = await response.json().catch(() => null);
                    throw new Error(errorDetail?.detail || `请求失败: HTTP ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    addMessage(data.response, false);
                } else {
                    throw new Error(data.detail || '后端服务处理失败');
                }
            } catch (error) {
                // 分类处理错误类型
                let errorMsg = '网络请求失败';
                
                if (error.name === 'AbortError') {
                    errorMsg = '响应超时，请稍后重试';
                } else if (error.message.includes('Failed to fetch')) {
                    errorMsg = '无法连接到服务器，请检查网络连接';
                } else {
                    errorMsg = `请求错误: ${error.message}`;
                }
                
                // 特殊处理file协议错误
                if (IS_FILE_PROTOCOL) {
                    errorMsg += "\n注意：您正在使用file://协议访问，需要启动本地后端服务";
                }
                
                // 显示错误提示
                addMessage(errorMsg, false, true);
            } finally {
                // 隐藏"正在输入"状态
                typingIndicator.style.display = 'none';
                updatePlaceholder();
            }
        }
        
        // 事件监听器
        sendButton.addEventListener('click', sendMessage);
        
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
        
        // 处理页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                checkConnection();
            }
        });
        
        // 初始化
        checkConnection();
        updatePlaceholder();
        userInput.focus();
        
        // 定时检查状态（每30秒）
        setInterval(checkConnection, 30000);
    </script>
</body>
</html>